package com.meiyuetao.util;

import com.jd.open.api.sdk.internal.util.StringUtil;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.*;

public class SignTool {

	public static String getSignStr(String seckey, Map<String, String> params) {
		Map<String, String> map = new HashMap<String, String>();
		for (String key : params.keySet()) {
			if (!key.equals("sign")) {
				map.put(key, params.get(key));
			}
		}
		 map.put("seckey", seckey);
		List<String> keys = new ArrayList<String>(map.keySet());
		Collections.sort(keys);
		StringBuffer sb = new StringBuffer();
		int count = keys.size();
		for (String s : keys) {
			sb.append(s);
			sb.append(":");
			if (!StringUtil.isEmpty(map.get(s))) {
				sb.append(map.get(s));
			}
			if (count > 1) {
				sb.append("|");
			}
			count--;
		}
		String sign = "";
		try {
			sign = toHexValue(encryptMD5(sb.toString().getBytes(
					Charset.forName("utf-8"))));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("md5 error");
		}
		return sign;
	}

	private static byte[] encryptMD5(byte[] data) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(data);
		return md5.digest();
	}

	private static String toHexValue(byte[] messageDigest) {
		if (messageDigest == null)
			return "";
		StringBuilder hexValue = new StringBuilder();
		for (byte aMessageDigest : messageDigest) {
			int val = 0xFF & aMessageDigest;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}
